<template>
  <a-modal
    :open="open"
    :width="800"
    title="退费"
    centered
    :closable="false"
    ok-text="确定"
    :ok-button-props="{ disabled: disabledState && businessData.bcyt_st !== 0, loading: loadingState }"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="cost-form-style pb-4" :label-col="{ style: { width: '100px' } }">
      <div class="flex justify-between items-center">
        <div>
          <div class="text-lg font-bold">
            <span class="">本次应退</span>
            <span class="text-red-500"> ￥{{ formatAmount(businessData.bcyt) }}</span>
          </div>
          <div class="font-medium mt-2">
            <span class="">医保退费</span>
            <span class="text-red-500"> ￥{{ formatAmount(businessData.bcyt_yb || 0) }}</span>
          </div>
          <div class="font-medium mt-2">
            <span class="">本次实退</span>
            <span class="text-red-500"> ￥{{ formatAmount(businessData.bcyt_st) }}</span>
          </div>
        </div>
        <div>
          <div class="in-title">
            原票据号：{{ businessData.pjhm }} <span class="ml-3"> 原收费流水号： {{ businessData.chargeTotleLsh }}</span>
          </div>
          <div class="in-title mt-2">
            原医保支付：￥{{ formatAmount(businessData.bcyt_yb) }} <span class=""> | 原自费支付：￥{{ formatAmount(businessData.bcyt_st) }}</span>
          </div>
          <div class="w-full in-title mt-2">{{ paymentInfo }}</div>
        </div>
      </div>
      <!-- <div class="mt-2" style="padding: 0 30px">
        <div class="w-full in-title">{{ paymentInfo }}</div>
      </div> -->
      <a-divider class="!mb-6 mt-4" />
      <!-- <div class="-my-2 text-red-500">*退费累计金额不可大于应退金额</div> -->
      <div class="flex flex-wrap mt-6">
        <a-form-item v-for="item in chargeTypeList" :key="item.id" :label="item.zffsmc" class="w-1/2">
          <a-input-group class="!flex">
            <a-input
              :key="item.zffsdm"
              v-model:value="formState[item.zffsdm]"
              :disabled="isDisabledAll || (item.zffsdm === 'vipzf' && isDisabledVip)"
              size="large"
              class="-mr-[1px]"
              placeholder="0.00"
              @blur="handlerBlur(item.zffsdm)"
              @change="handlerChangePrice(item.zffsdm)"
            >
              <template #prefix> <span class="text-gray-400">￥</span> </template>
            </a-input>
            <a-button
              :disabled="isDisabledAll || (item.zffsdm === 'vipzf' && isDisabledVip)"
              class="!w-10 !rounded-l-none"
              size="large"
              @click="onclickAllPrice(item)"
            >
              <template #icon><ArrowLeftOutlined class="text-gray-400 text-xs" /></template>
            </a-button>
          </a-input-group>
        </a-form-item>
      </div>
    </a-form>
    <a-form class="pr-7 pl-4 -mt-1">
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="memo" :rows="3" placeholder="请输入" />
      </a-form-item>
    </a-form>
    <a-divider />
  </a-modal>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { omitBy } from 'lodash-es'
import { message } from 'ant-design-vue'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  type: {
    type: String,
    default: () => 'zf'
  },
  businessData: {
    type: Object,
    default: () => ({})
  },
  chargeTitle: {
    type: String,
    default: () => ''
  },
  loadingState: {
    type: Boolean,
    default: () => false
  }
})

const memo = ref('')
const chargeTypeList = ref([])
const formState = ref({})
const paymentAmount = ref({})
const priceTotal = ref(0)
const disabledState = ref(true)
const paymentInfo = ref({})
const getOutpPayInfo = async () => {
  if (props.type === 'zf') {
    const res = await post('/outp/oupCharge/getOutpChargeDepositPayInfo', { pjhm: props.businessData.pjhm })
    if (res.code !== 0) return message.error(res.msg)
    paymentInfo.value = res.data
  } else {
    paymentInfo.value = props.chargeTitle
  }
}

const handlerChangePrice = (zffsdm = '') => {
  priceTotal.value = 0
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  for (const key in formState.value) {
    if (key !== '') {
      priceTotal.value = +formState.value[key] + priceTotal.value
    }
  }
  if (priceTotal.value > +props.businessData.bcyt_st) {
    message.error('退费累计金额不可大于应退金额')
    formState.value[zffsdm] = null
    return
  }

  if (Number(formatAmount(priceTotal.value)) === Number(props.businessData.bcyt_st)) {
    disabledState.value = false
  } else {
    disabledState.value = true
  }
  // for (const key in formState.value) {
  //   if (+formState.value[key] > 0) {
  //     disabledState.value = false
  //     return
  //   } else {
  //     disabledState.value = true
  //     return
  //   }
  // }
}

const handlerBlur = (zffsdm = '') => {
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
  }
}
const onclickAllPrice = (item) => {
  if (isDisabledVip.value) {
    formState.value = {}
    formState.value = { [item.zffsdm]: formatAmount(props.businessData.bcyt_st - props.businessData.vipzf), vipzf: formatAmount(props.businessData.vipzf) }
    disabledState.value = false
  } else {
    formState.value = {}
    formState.value = { [item.zffsdm]: formatAmount(props.businessData.bcyt_st) }
    disabledState.value = false
  }
}
const onRest = () => {
  formState.value = {}
  onVipReturn()
  chargeTypeList.value.forEach((item) => {
    paymentAmount.value[item.zffsdm] = 0
  })
}

const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  data.forEach((item) => {
    paymentAmount.value[item.zffsdm] = 0
  })
  chargeTypeList.value = data
}

const onOk = async () => {
  Object.keys(formState.value).forEach((i) => {
    Object.keys(paymentAmount.value).forEach((j) => {
      if (i === j) {
        paymentAmount.value[j] = formState.value[i]
      }
    })
  })
  const params = {
    ...paymentAmount.value,
    tkje: formatAmount(props.businessData.bcyt_st),
    pjhm: props.businessData.pjhm,
    memo: memo.value
  }
  const result = omitBy(params, (val) => val === null)
  emit('success', result)
}
const isDisabledAll = ref(false)
const isDisabledVip = ref(false)
const onVipReturn = () => {
  if (props.businessData.vipzf === 0 || !props.businessData.vipzf) return
  if (props.businessData.vipzf > props.businessData.bcyt_st || props.businessData.vipzf === props.businessData.bcyt_st) {
    formState.value.vipzf = formatAmount(props.businessData.bcyt_st)
    isDisabledAll.value = true
    disabledState.value = false
  } else {
    formState.value.vipzf = formatAmount(props.businessData.vipzf)
    isDisabledVip.value = true
  }
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      isDisabledAll.value = false
      isDisabledVip.value = false
      getOutpPayInfo()
      disabledState.value = true
    }
    onRest()
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  getChargeTypeList()
})
</script>
<style lang="less" scoped>
.cost-form-style {
  .charge-details {
    color: #8e8b8b;
    font-size: 13px;
  }
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;
      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }
    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;
      text-align: right;
      .ant-input {
        text-align: right;
      }
    }
  }
}
.in-title {
  color: #a4adb3;
}
</style>
